/*
 * @Description: 原文导入规则面板
 * @Author: Rfan
 * @Date: 2022-05-06 17:09:13
 * @LastEditTime: 2022-09-08 14:24:21
 */

import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Form, Radio, RadioChangeEvent } from 'antd';
import classNames from 'classnames/bind';
import { fetchMetadata } from '@/api/metadata';
import { useAccessionMgtContext } from '../../../../contexts/AccessionMgtContext';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import PathForm from './PathForm';
import NameForm from './NameForm';
import styles from '../../../../styles/uploadCDDialog.module.scss';

const cx = classNames.bind(styles);

const RulePane = forwardRef((props: any, ref: any) => {
  const { atId, rule, onClose } = props;
  const { activeBatch } = useAccessionMgtContext();

  const [ruleType, setRuleType] = useState(1);
  const [metadata, setMetadata] = useState<any>([]);
  const [pathForm] = Form.useForm();
  const [nameForm] = Form.useForm();

  useImperativeHandle(ref, () => ({
    save: () => {
      saveRules();
    }
  }));

  useEffect(() => {
    if (rule && rule.ruleType) {
      setRuleType(rule.ruleType);
    }

    if (atId) {
      const { atType, atCode } = activeBatch.archiveType;
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate: {
          atType,
          atCode,
          level: 1
        }
      };
      fetchMetadata(fieldQuery).then((res: any) => {
        setMetadata(res.data);
      });
    }
  }, [atId]);

  useEffect(() => {
    if (rule && rule.ruleType) {
      setRuleType(rule.ruleType);
    }
  }, [rule]);

  const onChange = (evt: RadioChangeEvent) => {
    setRuleType(evt.target.value);
  };

  const saveRules = () => {
    if (ruleType === 1) {
      pathForm.submit();
    } else {
      nameForm.submit();
    }
  };

  return (
    <div className={cx('rule-pane')}>
      <Radio.Group onChange={onChange} value={ruleType}>
        <Radio value={1}>按文件夹路径匹配</Radio>
        <Radio value={2}>按文件名匹配</Radio>
      </Radio.Group>

      <div className="form-wrap">
        {ruleType === 1 ? (
          <PathForm form={pathForm} data={rule.folderRule} metadata={metadata} onClose={onClose} />
        ) : (
          <NameForm
            form={nameForm}
            data={rule.fileNameRule}
            metadata={metadata}
            onClose={onClose}
          />
        )}
      </div>
    </div>
  );
});

export default RulePane;
